package org.example.command;

import org.example.model.HTMLDocument;
import org.jsoup.nodes.Document;

import java.io.IOException;

public class ReadCommand implements CanUndoCommand {
    private HTMLDocument htmlDocument;
    private String filepath;
    private Document previousDocument;  // 用于支持 undo 功能

    private ReadCommand(HTMLDocument htmlDocument, String filepath) {
        this.htmlDocument = htmlDocument;
        this.filepath = filepath;
    }

    public static Command create(HTMLDocument htmlDocument, String filepath){
        return  new ReadCommand(htmlDocument,filepath);
    }
    @Override
    public boolean execute() {
        try {
            // 保存当前的文档以便撤销时还原
            this.previousDocument = htmlDocument.getDocument().clone();
            // 从文件加载新的 HTML 文档
            htmlDocument.loadFromFile(filepath);
        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public void undo() {
        // 撤销时将之前的文档还原
        htmlDocument.setDocument(previousDocument);
    }
}
